<template>
  <section class="page-content">
    <div class="toolbar">
      <el-form :inline="true" :model="params">
        <el-form-item label="用户列表">
          <el-input v-model="searchData.account" size="small" placeholder="用户账号"></el-input>
        </el-form-item>
        <el-form-item label="角色">
          <el-select v-model="searchData.role" value-key="id" placeholder="请选择角色">
            <el-option
              v-for="item in roles"
              :key="item.id"
              :disabled="disabled(item)"
              :label="item.display_name + '(' + item.name + ')'"
              :value="item.name">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" size="small" icon="search" @click="onSubmit">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="success" size="small" icon="plus" @click="create">新增</el-button>
        </el-form-item>
      </el-form>
    </div>
    <el-table
      v-loading="loading"
      :data="tableData.data"
      @sort-change="sort"
      border
      style="width: 100%"
      max-height="100%">
      <el-table-column
        prop="id"
        width="80"
        sortable
        label="ID">
      </el-table-column>
      <el-table-column
        prop="avatar"
        width="80"
        sortable
        label="头像">
        <template slot-scope="scope">
          <img style="width:60px; border-radius:60px;" :src="scope.row.avatar" alt="" v-if="scope.row.avatar && scope.row.avatar.indexOf('http:') !== -1">
          <img style="width:60px; border-radius:60px;" :src="$serverUrl + '/storage/' + scope.row.avatar" alt="" v-if="scope.row.avatar && scope.row.avatar.indexOf('http:') === -1">
        </template>
      </el-table-column>
      <el-table-column
        prop="name"
        sortable
        label="姓名">
      </el-table-column>
      <el-table-column
        prop="account"
        sortable
        label="账号">
      </el-table-column>
      <el-table-column
        prop="integral"
        sortable
        label="积分">
      </el-table-column>
      <el-table-column
        prop="balance"
        sortable='custom'
        label="余额">
      </el-table-column>
      <el-table-column
        label="角色">
        <template slot-scope="scope">
          <el-tag
            class="tag"
            v-for="item in scope.row.roles" 
            :key="item.id"
            type="success">
            {{item.display_name}} 
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        prop="created_at"
        sortable
        label="注册时间">
      </el-table-column>
      <el-table-column
        fixed="right"
        width="220"
        label="操作">
        <template slot-scope="scope">
          <el-button
            @click.native.prevent="editRow(scope.row)"
            type="default"
            :disabled="disabled(scope.row.roles[0])"
            size="mini">
            编辑
          </el-button>
          <el-button
            @click.native.prevent="editUserRole(scope.row)"
            type="success"
            :disabled="disabled(scope.row.roles[0])"
            size="mini">
            角色
          </el-button>
          <el-button
            @click.native.prevent="deleteRow(scope.row)"
            type="danger"
            :disabled="disabled(scope.row.roles[0])"
            size="mini">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="block toolbar">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="tableData.current_page"
        :page-sizes="[10, 20, 30, 50]"
        :page-size="parseInt(tableData.per_page)"
        layout="total, sizes, prev, pager, next, jumper"
        :total="tableData.total">
      </el-pagination>
    </div>
    <!-- dialog create or edit user-->
    <el-dialog class="dialog" title="用户" :visible.sync="visible" width="850px">
      <el-form :model="formData" ref="formData" :rules="formRules"  label-width="70px">
        <el-form-item label="账号" prop="account">
          <el-input v-model="formData.account" :disabled="accountDisabled" placeholder="显示名称"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input type="password" v-model="formData.password" placeholder="留空则保留原密码"></el-input>
        </el-form-item>
        <el-form-item label="父级ID" prop="parent_id">
          <el-input v-model="formData.parent_id" placeholder="父账户ID"></el-input>
        </el-form-item>
        <el-form-item label="提成比例" prop="bonus_ratio">
          <el-input type="number" v-model="formData.bonus_ratio" placeholder="该设置值针对教师生效"></el-input>
        </el-form-item>
        <el-form-item label="装币" prop="zhuangbi">
          <el-input type="number" v-model="formData.zhuangbi" placeholder="装币"></el-input>
        </el-form-item>
        <el-form-item label="轻币" prop="qingbi">
          <el-input type="number" v-model="formData.qingbi" placeholder="轻币"></el-input>
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="formData.name" placeholder="姓名"></el-input>
        </el-form-item>
        <el-form-item label="角色">
          <el-select v-model="formData.roles_id" value-key="id" multiple placeholder="请选择角色">
            <el-option
              v-for="item in roles"
              :key="item.id"
              :disabled="disabled(item)"
              :label="item.display_name + '(' + item.name + ')'"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="等级">
          <el-select v-model="formData.level_id" value-key="id" placeholder="请选择等级">
            <el-option
              v-for="item in levels"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="头像" prop="avatar">
          <el-upload
            class="avatar-uploader"
            accept="image/*"
            :action="$serverUrl + '/api/upload/thumbImage'"
            name="file"
            :data="{width: 200, height: 200, folder: 'avatar'}"
            :show-file-list="false"
            :on-success="handleUploadSuccess"
            :before-upload="beforeUpload">
            <img v-if="formData.avatar" :src="avatar" class="upload-thumb">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="介绍" prop="details" label-position="top" style="max-width: 800px;">
          <tinymce :height="280" ref="editor" v-model="formData.details"></tinymce>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancleCreateOrEdit('formData')" :disabled="editLoading">取 消</el-button>
        <el-button type="primary" :loading="editLoading" @click="handleCreateOrEdit('formData')">确 定</el-button>
      </div>
    </el-dialog>

     <!-- dialog for user roles-->
    <el-dialog class="dialog" title="设置角色" :visible.sync="roleDialogVisible">
      <el-form label-width="100px">
        <el-form-item label="选择角色">
          <el-select v-model="userRoles" multiple placeholder="请选择角色">
            <el-option
              v-for="item in roles"
              :key="item.id"
              :disabled="disabled(item)"
              :label="item.display_name + '(' + item.name + ')'"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="roleDialogVisible = false" :disabled="editLoading">取 消</el-button>
        <el-button type="primary" :loading="editLoading" @click="handleSetUserRoles">确 定</el-button>
      </div>
    </el-dialog>

  </section>
</template>
<script>
  import {generateUrl} from '@/utils/helpers'
  import Tinymce from '@/components/tinymce/Editor'
  export default {
    data () {
      return {
        accountDisabled: true,
        loading: false,
        tableData: {
          first_page_url: '',
          from: '',
          to: '',
          last_page: '',
          last_page_url: '',
          next_page_url: '',
          prev_page_url: '',
          path: '',
          per_page: 0,
          total: 0,
          data: []
        },
        searchData: {
          account: '',
          role: ''
        },
        params: {
          order_by: 'id',
          order_type: 'desc',
          page_size: 20,
          account: '',
          role: '',
          page: 1
        },
        levels: [],
        // dialog create or edit user
        editLoading: false,
        visible: false,
        tempData: {
          id: null,
          name: '',
          roles_id: [],
          account: '',
          avatar: '',
          level_id: 1,
          parent_id: 0,
          zhuagnbi: 0,
          qingbi: 0,
          details: null,
          roles: []
        },
        formData: {},
        formRules: {
          name: [
            { required: true, message: '请输入姓名', trigger: 'blur' },
            { min: 1, max: 20, message: '长度在 1 到 20 个字符', trigger: 'blur' }
          ],
          account: [
            { required: true, message: '请输入显示账号', trigger: 'blur' },
            { min: 1, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
          ],
          parent_id: [
            { required: true, message: '请输入父账户ID', trigger: 'blur' }
          ]
        },
        // dialog change user roles
        roleDialogVisible: false,
        roles: [],
        user_id: null,
        userRoles: []
      }
    },
    components: { Tinymce },
    computed: {
      avatar () {
        if (this.formData.avatar.indexOf('http:') === -1) {
          return this.$serverUrl + '/storage/' + this.formData.avatar
        }
        return this.formData.avatar
      }
    },
    mounted () {
      this._restFormData()
      this._getData()
      this._getRoles()
      this._getLevels()
    },
    watch: {
      params: {
        deep: true,
        handler (newValue) {
          this._getData()
        }
      }
    },
    methods: {
      handleUploadSuccess (res, file) {
        console.log(res)
        this.formData.avatar = res
      },
      beforeUpload (file) {
        const isLt1M = file.size / 1024 / 1024 < 1
        if (!isLt1M) {
          this.$message.error('上传头像图片大小不能超过 1MB!')
        }
        return isLt1M
      },
      disabled (item) {
        if (!item || !item.name) return false
        return item.name === 'Developer' || item.name === 'Admin'
      },
      deleteRow (row) {
        this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.loading = true
          this.$http.delete('/users/' + row.id).then((response) => {
            this.loading = false
            this.$message.success('删除成功')
            this._getData()
          }).catch((error) => {
            this.loading = false
            console.log(error)
          })
        }).catch((error) => {
          console.log(error)
        })
      },
      editRow (item) {
        this.accountDisabled = true
        item.roles_id = this._generateRolesId(item.roles)
        this.formData = Object.assign({}, item)
        // this.formData.roles_id = this._generateRolesId(item.roles)
        this.visible = true
      },
      editUserRole (item) {
        this.user_id = item.id
        this.userRoles = this._generateRolesId(item.roles)
        this.roleDialogVisible = true
      },
      handleSetUserRoles () {
        if (this.user_id) {
          this.editLoading = true
          this.$http.put(`/users/${this.user_id}/roles`, {roles: this.userRoles}).then((response) => {
            this.$message.success(response.data.message)
            this.editLoading = false
            this.roleDialogVisible = false
            this._getData()
          }).catch((error) => {
            this.editLoading = false
            this.roleDialogVisible = false
            console.log(error)
          })
        }
      },
      onSubmit () {
        this.params.account = this.searchData.account
        this.params.role = this.searchData.role
      },
      handleSizeChange (val) {
        this.params.page_size = val
      },
      handleCurrentChange (val) {
        this.params.page = val
      },
      sort (data) {
        let orderType = ''
        if (data.order === 'ascending') {
          orderType = 'asc'
        }
        if (data.order === 'descending') {
          orderType = 'desc'
        }
        this.params.order_type = orderType
        this.params.order_by = data.prop
      },
      create () {
        this._restFormData()
        this.accountDisabled = false
        this.visible = true
      },
      cancleCreateOrEdit (formName) {
        this.visible = false
        this.$refs[formName].resetFields()
      },
      handleCreateOrEdit (formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            this.$http({
              method: this.formData.id === null ? 'post' : 'put',
              url: this.formData.id === null ? '/users' : '/users/' + this.formData.id,
              data: this.formData
            }).then((response) => {
              this.$message.success(response.data.message)
              this.editLoading = false
              this.visible = false
              this._getData()
            }).catch((error) => {
              this.editLoading = false
              console.log(error)
            })
          } else {
            console.log('error submit!!')
            return false
          }
        })
      },
      _restFormData () {
        this.formData = Object.assign({}, this.tempData)
      },
      _getData () {
        let url = generateUrl('/users', this.params)
        this.loading = true
        this.$http.get(url).then((response) => {
          this.loading = false
          this.tableData = response.data
        }).catch((error) => {
          this.loading = false
          console.log(error)
        })
      },
      _getRoles () {
        this.$http.get('/roles?page_size=1000').then((response) => {
          this.roles = response.data.data
        }).catch((error) => {
          console.log(error)
        })
      },
      _getLevels () {
        this.$http.get('/levels').then((response) => {
          this.levels = response.data
        }).catch((error) => {
          console.log(error)
        })
      },
      _generateRolesId (arr) {
        let userRoles = []
        arr.forEach((v) => {
          userRoles.push(v.id)
        })
        return userRoles
      }
    }
  }
</script>
<style lang="scss" scoped>
  .dialog {
    .el-select {
      width: 80%;
    }
    .el-input {
      width: 80%;
    }
    .el-textarea {
      width: 80%;
    }
  } 
  .tag {
    margin-right: 5px;
  }
</style>
